export async function retry<T = any>(fn: () => (T | Promise<T>), times = 3, error: (err: any) => void) {
  let res: T;
  let err: any;
  for (let i = 0; i < times; i++) {
    try {
      res = await fn()
      return res
    } catch (e) {
      if (error) error(e)
      err = e
    }
  }
  throw err;
}

export const toInt = (str: any) => typeof str === 'number' ? str : parseInt(str, 10)

export const dateFormatter = (raw: number | string) => {
  if (typeof raw === 'number' && raw < 946684800000) raw *= 1000
  const date = new Date(raw)
  const Y = date.getFullYear().toString().padStart(4, '0')
  const M = (date.getMonth() + 1).toString().padStart(2, '0')
  const D = date.getDate().toString().padStart(2, '0')
  const h = date.getHours().toString().padStart(2, '0')
  const m = date.getMinutes().toString().padStart(2, '0')
  const s = date.getSeconds().toString().padStart(2, '0')

  return `${Y}-${M}-${D} ${h}:${m}:${s}`
}

export function emptyFilter<T extends Object>(data: T, emptyValues: any[] = ['', undefined, null]) {
  const patch: any = {};
  for (let [k, v] of Object.entries(data)) {
    if (!emptyValues.includes(v)) {
      patch[k] = v
    }
  }
  return patch as T
}

export function round(num: number, precision = 2) {
  return Math.round(num * (10 ** precision)) / (10 ** precision)
}
